package calao.client;

import java.util.Iterator;

import calao.client.ServiceCallback;
import calao.client.i18n.Text;
import calao.client.ui.HasLinks;
import calao.client.ui.HasTitle;
import calao.client.ui.Link;

import com.google.gwt.user.client.ui.FlowPanel;

public class ProfileTable
extends FlowPanel
implements HasTitle, HasLinks
{
	
	ProfileInfo[] list = {};

	final Text text = Desktop.getDesktop().text;
	
	class ProfileLink extends Link {
		final ProfileInfo target;
		ProfileLink(ProfileInfo target) {
			super(target.name);
			this.target = target;
		}
		protected void onClick() {
			Desktop.getDesktop().stackView(new ProfileForm(ProfileTable.this, target));
		}
	}
	
	class CreateLink extends Link {
		CreateLink() {
			super(text.newProfile());
		}
		protected void onClick() {
			Desktop.getDesktop().stackView(new ProfileForm(ProfileTable.this));
		}
	}
	
	ProfileTable()
	{
		setTitle(text.profiles());
		refresh();
	}
		
	void buildLinks()
	{
		clear();
		for (int i=0; i<list.length; i++) add(new ProfileLink(list[i]));
	}

	public Link[] getLinks() {
		return new Link[] { new CreateLink() };
	}
	
	void created(ProfileInfo Profile)
	{
		refresh();
	}
	
	private void refresh()
	{
		Desktop.getDesktop().memberService.listProfiles(new ServiceCallback() {
			protected void onReturn(Object result) {
				list = (ProfileInfo[])result;
				buildLinks();
			}
		});
	}
	
	void modified(ProfileInfo profile)
	{
		Iterator iter = getChildren().iterator();
		while (iter.hasNext()) {
			ProfileLink link = (ProfileLink)iter.next();
			if (link.target.id==profile.id) {
				link.target.name = profile.name;
				link.target.permissionNames = profile.permissionNames;
				link.setText(profile.name);
			}
		}
	}
	
	void deleted(ProfileInfo profile)
	{
		refresh();
	}
	
}
